package com.solocredit.finance.http

import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.net.InetAddress

class HttpDnsV3(val tempHost: String) {

    suspend fun lookupSys2(onResult: (String) -> Unit) {
        withContext(Dispatchers.IO) {
            val finalHost = tempHost.replaceFirst("^(https?://)".toRegex(), "");
            try {
                val addresses = InetAddress.getAllByName(finalHost)
                for (address in addresses) {
                    val ipAddress = address.hostAddress
                    if (!ipAddress.isNullOrBlank()) {
                        Log.d(HttpDnsV3::class.java.simpleName, "lookup: $ipAddress")
                        withContext(Dispatchers.Main) {
                            onResult.invoke(ipAddress)
                        }
                        break
                    }
                }
            } catch (e: Exception) {
                throw RuntimeException("Failed to resolve hostname: " + finalHost + " , " + e.localizedMessage)
            }
        }
    }
}